<template>
  <div class="user_class">
    <el-tree ref="tree" class="user_tree" v-loading="TreeLoading" :check-on-click-node="true" :data="Treedata"
      :expand-on-click-node="false" :props="defaultProps" default-expand-all highlight-current node-key="departmentUuid"
      @node-click="handleNodeClick">
    </el-tree>
    <div style="width: calc(100% - 300px); height: 100%; padding: 0 0 0 20px">
      <el-form v-show="showSearch" :inline="true" :model="searchForm" class="demo-form-inline" size="small"
        label-suffix="：">
        <el-form-item label="员工名称">
          <el-input v-model="searchForm.accountName" clearable placeholder="请输入员工名称"></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="searchForm.accountNum" clearable placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phoneNum" clearable placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <!-- 操作 -->
      <div class="dis-o-between operate-line">
        <div>
          <el-button icon="el-icon-plus" plain type="primary" @click="addUser" size="small">新增</el-button>
          <el-button icon="el-icon-search" type="primary" @click="reqTableData(1)" size="small">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetReq()" size="small">重置</el-button>
        </div>
        <RightToolbar :showSearch.sync="showSearch" @queryTable="reqTableData(1)"></RightToolbar>
      </div>
      <!-- 表格 -->
      <el-table v-loading="loading" :data="tableData">
        <el-table-column v-for="(item, index) in tableTitle" :key="index" :prop="item.prop" :label="item.label"
          :type="item.type" :fixed="item.fixed ? item.fixed : null" :align="item.align" :width="item.width">
          <template slot-scope="scope">
            <div v-if="['img'].includes(item.prop)">
              <el-image v-if="scope.row.img" :src="scope.row.img" fit="fit" style="width: 100px; height: 100px">
                <div slot="error" class="image-slot"></div>
              </el-image>
            </div>
            <div v-else-if="item.prop === 'sex'">
              {{ sexList[Number(scope.row.sex)].label }}
            </div>
            <div v-else-if="item.prop === 'roleList'">
              {{ getRoleName(scope.row) }}
            </div>
            <div v-else-if="item.prop === 'post'">
              {{ getPost(scope.row) }}
            </div>
            <div v-else>{{ scope.row[item.prop] }}</div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120px" align="center">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="edit(scope.row)">编辑</el-button>
            <el-button size="small" type="text" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--描述：分页-->
      <paginationCom :pagination="pagination" @handleSizeChange="handleSizeChange"
        @handleCurrentChange=handleCurrentChange>
      </paginationCom>
      <!-- 弹框 -->
      <el-dialog v-dialogDrag :title="title" :visible.sync="dialogFormVisible" width="800px">
        <el-form ref="refForm" :model="ruleForm" :rules="formRules" label-position="right" label-width="120px" inline>
          <el-row>
            <el-col :span="12">
              <el-form-item label="账户名称" prop="accountName">
                <el-input v-model="ruleForm.accountName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账号" prop="accountNum">
                <el-input v-model="ruleForm.accountNum"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item v-if="title == '新增'" label="密码" prop="password">
                <el-input v-model="ruleForm.password"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phoneNum">
                <el-input v-model="ruleForm.phoneNum"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="身份证号码" prop="idNo">
                <el-input v-model="ruleForm.idNo"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别">
                <el-radio-group v-model="ruleForm.sex">
                  <el-radio v-for="item in sexList" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="部门" prop="departmentUuid">
                <el-cascader ref="cascaderAddr" @change="checked" style="width: 100%" v-model="ruleForm.departmentUuid"
                  :options="Treedata" :props="{
                    checkStrictly: true,
                    children: 'list',
                    value: 'departmentUuid',
                    label: 'departmentName',
                  }" clearable></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属角色" prop="roleUuids">
                <el-cascader style="width: 100%" v-model="ruleForm.roleUuids" :options="roleList" :props="roleListprops"
                  clearable></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <!-- 数据范围 -->
              <!-- <el-form-item label="数据范围" prop="dataRange">
                <el-select v-model="ruleForm.dataRange" placeholder="请选择" clearable filterable>
                  <el-option v-for="item in data_rangeOptions" :key="item.itemValue" :label="item.itemText"
                    :value="item.itemValue * 1">
                  </el-option>
                </el-select>
                <el-form-item prop="dataRanges" v-show="this.ruleForm.dataRange == '2' ? true : false">
                  <el-cascader style="width: 100%" v-model="ruleForm.dataDeptList" :options="Treedata" :props="{
                    checkStrictly: true,
                    children: 'list',
                    value: 'departmentUuid',
                    label: 'departmentName',
                    multiple: true,
                  }" clearable></el-cascader>
                </el-form-item>
              </el-form-item> -->
            </el-col>
            <el-col :span="12">
              <!-- 所属岗位 -->
              <el-form-item label="所属岗位" prop="post">
                <el-select v-model="ruleForm.post" placeholder="请选择" clearable filterable>
                  <el-option v-for="item in postOptions" :key="item.itemValue" :label="item.itemText"
                    :value="item.itemValue * 1">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <!-- 绑定仓库 -->
              <el-form-item label="绑定仓库" v-show="this.ruleForm.post == 3 ? true : false" prop="storehouseUuid">
                <el-select v-model="ruleForm.storehouseUuid" placeholder="请选择" clearable filterable>
                  <el-option v-for="item in storehouseOptions" :key="item.storehouseCode" :label="item.storehouseName"
                    :value="item.storehouseCode">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">

            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="头像">
                <img-upload ref="imgUpload" :imageUrl="ruleFormImg" :limit="1"></img-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">

            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <!-- 新增并置空 -->
          <!-- <el-button @click="addContinue('refForm')" v-show="this.title == '新增' ? true : false">确定并继续</el-button> -->
          <el-button type="primary" @click="addSubmit('refForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import ImgUpload from "@/components/upLoad/imgUpload.vue";
import md5 from "js-md5";
export default {
  name: 'user',
  data() {
    return {
      // tree
      node: null, //点击树的数据
      TreeLoading: false,
      Treedata: [], //树数据
      defaultProps: {
        children: "list",
        label: "departmentName",
      },

      // table数据
      // 搜索数据
      showSearch: true,
      searchForm: {},
      loading: false,
      tableData: [],
      tableTitle: [
        { prop: 'accountName', label: '账户名称', width: '100', align: 'center', fixed: "", type: "" },
        { prop: 'accountNum', label: '账号', width: '100', align: 'center', fixed: "", type: "" },
        { prop: 'departmentName', label: '部门名称', width: '', align: 'center', fixed: "", type: "" },
        { prop: 'phoneNum', label: '手机号', width: '110', align: 'center', fixed: "", type: "" },
        { prop: 'idNo', label: '身份证号码', width: '180', align: 'center', fixed: "", type: "" },
        { prop: 'img', label: '头像', width: '100', align: 'center', fixed: "", type: "" },
        { prop: 'sex', label: '性别', width: '80', align: 'center', fixed: "", type: "" },
        { prop: 'roleList', label: '角色', width: '280', align: 'center', fixed: "", type: "" },
        { prop: 'post', label: '岗位', width: '100', align: 'center', fixed: "", type: "" },
      ],
      // 分页
      pagination: {
        total: 0,
        per_page: 10,
        from: 1,
        to: 0,
        current_page: 1, //当前页数
      },




      // 新增修改用户信息
      title: "",
      dialogFormVisible: false,
      // 岗位列表
      postOptions: [],
      // 管理全局数据列表
      data_rangeOptions: [],
      // 仓库列表
      storehouseOptions: [],
      sexList: [
        { label: "男", value: 0 },
        { label: "女", value: 1 },
      ],
      roleList: [], //角色列表
      roleListprops: {
        label: "roleName",
        children: "childRole",
        value: "roleUuid",
        leaf: "leaf",
        multiple: true,
      },

      ruleForm: {},
      ruleFormImg: [],
      ruleFormDepartmentUuid: [],
      formRules: {
        accountName: [
          { required: true, message: "请输入账户名称", trigger: "blur" },
        ],
        accountNum: [
          { required: true, message: "请输入账号", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        departmentUuid: [
          { required: true, message: "请选择部门", trigger: "change" },
        ],
        roleUuids: [
          { required: true, message: "请选择角色", trigger: "change" },
        ],
        idNo: [
          {
            required: true,
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: "请输入正确的身份证号码",
            trigger: "blur",
          },
        ],
        phoneNum: [
          {
            pattern: /^\d{11}$/,
            message: "请输入11位手机号",
            trigger: "blur",
          },
        ],
      },
    };
  },
  props: {},

  components: { ImgUpload },

  created() { },

  mounted() {
    this.getRoleList();
    this.searchTree();
    this.getPostList();
    this.getData_rangeList();
    this.getStorehouseList();
  },

  beforeDestroy() { },

  methods: {
    searchTree() {
      this.TreeLoading = true;
      this.sendPost(
        "/enterpriseDepartment/getEnterpriseDepartmentTree",
        {}
      ).then((res) => {
        if (res.errcode == 0) {
          this.Treedata = res.data.list || [];
          this.Treedata.unshift({
            departmentName: "全部",
            departmentUuid: "quanbu",
            list: [],
            leaf: true,
          });
          this.Treedata.forEach((item1) => {
            item1.disabled = true;
            if (item1.list.length !== 0) {
              item1.list.forEach((item2) => {
                if (item2.list.length !== 0) {
                  item2.list.forEach((item3) => {
                    if (item3.list.length !== 0) {
                      item3.list.forEach((item4) => {
                        if (item4.list.length !== 0) {
                          item4.list.forEach((item5) => {
                            delete item5.list;
                          });
                        } else {
                          delete item4.list;
                        }
                      });
                    } else {
                      delete item3.list;
                    }
                  });
                } else {
                  delete item2.list;
                }
              });
            } else {
              delete item1.list;
            }
          });

          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.Treedata[0].departmentUuid);
            this.node = { ...this.Treedata[0], level: 1 };
            this.reqTableData(1);
          });
        } else {
          this.err({ message: res.errmsg });
        }
        this.TreeLoading = false;
      });
    },
    getAllAccountInfo(page) {
      if (page) {
        this.pagination.current_page = page;
      }
      this.loading = true;
      let data = {
        ...this.searchForm,
        pageNum: this.pagination.current_page,
        pageSize: this.pagination.per_page,
      };
      this.sendPost("/accountInfo/getAllAccountInfo", data).then((res) => {
        if (res.errcode == 0) {
          this.tableData = res.data.voList;
          this.pagination.total = res.data.total;
        } else {
          this.err({ message: res.errmsg });
        }
        this.loading = false;
      });
    },
    //获取企业下所有账号信息
    getAllAccountInfoByEnterpriseUuid(page) {
      if (page) {
        this.pagination.current_page = page;
      }
      this.loading = true;
      let data = {
        ...this.searchForm,
        pageNum: this.pagination.current_page,
        pageSize: this.pagination.per_page,
        departmentUuid: this.node.departmentUuid,
      };
      this.sendPost(
        "/accountInfo/getAllAccountInfoByEnterpriseUuid",
        data
      ).then((res) => {
        if (res.errcode == 0) {
          this.tableData = res.data.voList;
          this.pagination.total = res.data.total;
        } else {
          this.err({ message: res.errmsg });
        }
        this.loading = false;
      });
    },
    //获取部门下所有账号信息
    getAllAccountInfoByDepartmentUuid(page) {
      if (page) {
        this.pagination.current_page = page;
      }
      this.loading = true;
      let data = {
        ...this.searchForm,
        pageNum: this.pagination.current_page,
        pageSize: this.pagination.per_page,
        departmentUuid: this.node.departmentUuid,
      };
      this.sendPost(
        "/accountInfo/getAllAccountInfoByDepartmentUuid",
        data
      ).then((res) => {
        if (res.errcode == 0) {
          this.tableData = res.data.voList;
          this.pagination.total = res.data.total;
        } else {
          this.err({ message: res.errmsg });
        }
        this.loading = false;
      });
    },

    handleSizeChange(val) {
      this.pagination.per_page = val;
      this.reqTableData(1);
    },
    handleCurrentChange(val) {
      this.pagination.current_page = val;
      this.reqTableData();
    },
    addUser() {
      this.title = "新增";
      this.$refs.refForm ? this.$refs.refForm.resetFields() : undefined
      this.ruleFormImg = [];
      this.ruleForm = {
        departmentUuid: this.ruleFormDepartmentUuid,
        dataRange: 1,
      };
      this.dialogFormVisible = true;
    },
    edit(row) {
      // console.log(row);
      this.title = "编辑";
      this.ruleFormImg = [];
      this.ruleForm = JSON.parse(JSON.stringify(row));
      // this.ruleForm.departmentUuid = [JSON.parse(JSON.stringify(row)).departmentUuid]
      // this.ruleForm.roleUuids = []
      if (this.ruleForm.img) {
        this.ruleFormImg = [{ url: this.ruleForm.img }];
      }

      // this.ruleForm.departmentUuid = '';

      // 所属角色
      this.ruleForm.roleUuids = [];
      if (this.ruleForm.roleList && this.ruleForm.roleList.length !== 0) {
        this.ruleForm.roleList.forEach((ele) => {
          this.roleList.forEach((item) => {
            let a = item.childRole.find((item2) => {
              return item2.roleUuid == ele.roleUuid;
            });
            if (a) {
              this.ruleForm.roleUuids.push([item.roleUuid, ele.roleUuid]);
            }
          });
        });
      }

      // 自定义部门  2为自定义
      // console.log(this.ruleForm.dataRange);
      if (this.ruleForm.dataRange == 2) {
        this.ruleForm.dataDeptList = JSON.parse(this.ruleForm.dataRanges);
      }

      // console.log(this.ruleForm);
      this.dialogFormVisible = true;
    },
    del(row) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.sendGet("/accountInfo/dleteAccountInfo", { id: row.id }).then(
            (res) => {
              if (res.errcode == 0) {
                this.suc({ message: res.errmsg });
                this.reqTableData();
              } else {
                this.err({ message: res.errmsg });
              }
            }
          );
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除" });
        });
    },
    addSubmit(formName) {
      // console.log(this.ruleForm);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let roleUuids = [];
          this.ruleForm.roleUuids.forEach((val) => {
            roleUuids.push(val[1]);
          });
          this.ruleForm.roleUuids = roleUuids;

          if (this.ruleForm.dataRange == "2") {
            // 自定义部门
            delete this.ruleForm.dataRangeString;
            this.ruleForm.dataRanges = JSON.stringify(
              this.ruleForm.dataDeptList
            );
            // console.log(this.ruleForm.dataRanges);
            let dataDeptList = [];
            this.ruleForm.dataDeptList.forEach((val) => {
              // console.log(val);
              dataDeptList.push(val[1]);
            });
            this.ruleForm.dataDeptList = dataDeptList;
          } else {
            this.ruleForm.dataRanges = "";
            delete this.ruleForm.dataRangeString;
            delete this.ruleForm.dataDeptList;
          }

          if (
            Object.prototype.toString
              .call(this.ruleForm.departmentUuid)
              .indexOf("Array") !== -1
          ) {
            let departmentUuid =
              this.ruleForm.departmentUuid[
              this.ruleForm.departmentUuid.length - 1
              ];
            this.ruleForm.departmentUuid = departmentUuid;
          }
          if (this.ruleFormImg && this.ruleFormImg.length !== 0) {
            this.ruleForm.img = this.ruleFormImg[0].url;
          } else {
            this.ruleForm.img = null;
          }

          //所属岗位
          if (this.ruleForm.post !== null) {

          } else {
            this.ruleForm.post = null;
          }
          // 管理数据
          if (this.ruleForm.dataRange !== null) {

          } else {
            this.ruleForm.dataRange = null;
          }

          if (this.title == "新增") {
            this.ruleForm.password = md5.hex(this.ruleForm.password);
          }
          this.sendPost(
            "/accountInfo/insertOrUpdateAccountInfo",
            this.ruleForm
          ).then((res) => {
            if (res.errcode == 0) {
              this.suc({ message: res.errmsg });
              this.form = {};
              this.reqTableData(1);
              this.getAllAccountInfo();
            } else {
              this.err({ message: res.errmsg });
            }
          });
        } else {
          // console.log("error submit!!");
          return false;
        }
        this.dialogFormVisible = false;
      });
    },
    getData(e, list) {
      if (e.parent !== null) {
        list.unshift(e.data.departmentUuid);
        this.getData(e.parent, list);
        return list;
      } else {
        return list;
      }
    },
    handleNodeClick(node, e) {
      // console.log(node);
      let data2 = this.getData(e, []);
      this.ruleFormDepartmentUuid = data2;
      this.node = node;
      this.node.level = e.level;
      this.reqTableData(1);
    },
    resetReq() {
      this.searchForm = {};
      this.getAllAccountInfo(1);
    },
    reqTableData(page) {
      // console.log(page);
      if (this.node.departmentName == "全部") {
        this.getAllAccountInfo(page);
      } else {
        if (this.node.level == 1) {
          this.getAllAccountInfoByEnterpriseUuid(page);
        } else {
          this.getAllAccountInfoByDepartmentUuid(page);
        }
      }
    },
    getRoleList() {
      this.sendPost("/role/list").then((res) => {
        if (res.errcode == 0) {
          // console.log(res);
          this.roleList = res.data.voList;
          this.roleList.forEach((item) => {
            if (item.childRole == null || item.childRole.length == 0) {
              item.leaf = true;
            } else {
              item.leaf = false;
              item.childRole.forEach((ele) => {
                delete ele.childRole;
                ele.leaf = true;
              });
            }
          });
        } else {
          this.err({ message: res.errmsg });
        }
        this.loading = false;
      });
    },
    // 获取岗位列表
    getPostList() {
      this.sendGet("/dictItem/getDictItemByDictCode", {
        dictCode: "post",
      }).then((res) => {
        if (res.errcode == 0) {
          // console.log(res);
          this.postOptions = res.data;
          // console.log(this.postOptions);
        } else {
          this.err({ message: res.errmsg });
        }
      });
    },
    // 获取管理数据列表
    getData_rangeList() {
      this.sendGet("/dictItem/getDictItemByDictCode", {
        dictCode: "data_range",
      }).then((res) => {
        if (res.errcode == 0) {
          // console.log(res);
          this.data_rangeOptions = res.data;
        } else {
          this.err({ message: res.errmsg });
        }
      });
    },
    // 获取仓库列表
    getStorehouseList() {
      this.sendPost("/storehouse/getStorehouseByObj", {}).then((res) => {
        // console.log(res);
        if (res.errcode == 0) {
          this.storehouseOptions = res.data.list;
        } else {
          this.err({ message: res.errmsg });
        }
      });
    },
    getRoleName(row) {
      let data = [];
      if (row.roleList.length !== 0) {
        row.roleList.forEach((ele) => {
          data.push(ele.roleName);
        });
        return data.join(",");
      } else {
        return "";
      }
    },
    // 岗位
    getPost(row) {
      let data = [];
      // console.log(row);
      if (row.post !== null) {
        data = row.postString;
        return data;
      } else {
        return "";
      }
    },
    // 新增并置空
    addContinue(refForm) {
      this.addSubmit(refForm);
      this.ruleForm = {};
      this.dialogFormVisible = true;
      // this.$refs[refForm].resetFields();
    },
    checked() {
      // console.log("checked");
      let a = this.$refs["cascaderAddr"].getCheckedNodes();
      // console.log("departmentUuid", a);
      if (a.length > 0) {
        // console.log(a[0].data.departmentName);
        this.ruleForm.departmentName = a[0].data.departmentName;
      }
    },
  },

  computed: {},

  watch: {},

  directives: {},

  filters: {}
};
</script>

<style scoped lang="scss">
.user_class {
  width: 100%;
  height: 100%;
  display: flex;

  .user_tree {
    width: 300px;
    height: 100%;
  }
}
</style>
